
//消抖
export const debounce = (func: (...args: any[]) => void, delay: number) => {
    let timer: NodeJS.Timeout | null = null;
    return (...args: any[]) => {
        if (timer) {
            clearTimeout(timer)
        }
        timer = setTimeout(() => {
            func(...args);
        }, delay)
    }
}

//节流
export const throttle = (func: (...args: any[]) => void, limit: number) => {
    let inThrottle: boolean = false;
    return (...args: any[]) => {
        if (!inThrottle) {
            func(...args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit)
        }
    }
}

//raf重绘节流，在下一次浏览器重新前调用函数，减少重绘次数，提升性能
type TCallback = (...args: any[]) => void
interface RafThrottleFn extends TCallback {
    cancel: () => void,
}
export function rafThrottle(callback: TCallback): RafThrottleFn {
    let requestId: number | null = null;
    const throttled: RafThrottleFn = (...args) => {
        const later = () => {
            requestId = null;
            callback(...args);
        };
        if (requestId === null) {
            requestId = requestAnimationFrame(later)
        }
    }
    throttled.cancel = () => {
        if (requestId !== null) {
            cancelAnimationFrame(requestId)
        }
        requestId = null
    }

    return throttled
}
